/**********************************************************************
* 函数名称： // LS_handle
* 功能描述： // LS命令
* 访问的表： // fileInfo
* 修改的表： // NULL
* 输入参数： // const char* p_user, const char *p_name, int netfd
* 返回的值： // 正确返回0， 错误返回1
* 更新说明： // 输出按字典顺序排序
* 修改日期        版本号     修改人          修改内容
* -----------------------------------------------
* 2023/04/16       V3.4       zhao            XXXX
***********************************************************************/
#include <func.h>

int LS_handle(const char* p_user, const char *p_name, int netfd) {
    train_t train;
    bzero(train.data, sizeof(train.data));

    MYSQL * mysql = mysql_init(NULL); // 为mysql连接分配内存（线程不安全）

    MYSQL * ret = mysql_real_connect(mysql,"localhost", "root", "123456", "test", 0, NULL, 0);  //密码、数据库名可能不同
    if(ret == NULL){
        train.length = -1;
        sprintf(train.data, "mysql connect error:%s\n", mysql_error(mysql));
        
        send(netfd, &train.length, sizeof(int), 0);
        send(netfd, train.data, strlen(train.data), 0);
        SYSLOG(p_user, "LS", p_name,"fail");

        return -1;
    }

    char sql[1024] = "select name, id, pre_id, user, tomb from fileInfo ORDER BY name;";
    int qret = mysql_query(mysql,sql);
    if(qret != 0){
        fprintf(stderr,"sql error:%s\n", mysql_error(mysql));
        train.length = -1;
        sprintf(train.data, "mysql connect error:%s\n", mysql_error(mysql));
        send(netfd, &train.length, sizeof(int), 0);
        send(netfd, train.data, strlen(train.data), 0);
        SYSLOG(p_user, "LS", p_name,"fail");

        return -1;
    }

    MYSQL_RES *result = mysql_store_result(mysql); //取出读取的结果
    char buf[30] = {0};
    MYSQL_ROW row1, row2; //MYSQL_ROW 为char**

    unsigned int temp = 1;
    while((row1 = mysql_fetch_row(result)) != NULL){
        bzero(buf, sizeof(buf));
        if(strcmp(row1[0], p_name) == 0 && strcmp(row1[3], p_user) == 0) {
            strcpy(buf, row1[1]);
            break;
        }else {
            temp++;
            if(temp == mysql_num_fields(result)) {
                train.length = -1;
                sprintf(train.data, "%s is empty\n", p_name);
                send(netfd, &train.length, sizeof(int), 0);
                send(netfd, train.data, strlen(train.data), 0);
                SYSLOG(p_user, "LS", p_name,"fail");
            }
            continue;
        }
    }

    char info[1024] = {0};
    while((row2 = mysql_fetch_row(result)) != NULL){
        bzero(info, sizeof(info));
        if(strcmp(row2[2], buf) == 0 && strcmp(row2[3], p_user) == 0 && atoi(row2[4]) != 1) {
            sprintf(info, "%s%c", row2[0], ' ');
            strcat(train.data, info);
        }else {
            continue;
        }
    }

    train.length = 0;
    send(netfd, &train.length, sizeof(int), 0);
    send(netfd, train.data, strlen(train.data), 0);
    SYSLOG(p_user, "LS", p_name,"success");

    mysql_free_result(result);
    mysql_close(mysql);
    return 0;
}